﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Data;
using ChatJs.Net;
using DataMongo;
using DataMongo.Entities;
using Google.GData.Contacts;
using DataMongo.Entities;

using WebMatrix.WebData;


namespace MVCMongo.Services
{
    public static class UtilityService
    {
        public static string GetImageUrlFromSite(string stringUrl)
        {
            string htmlCode = string.Empty;
            using (WebClient client = new WebClient())
            {
                htmlCode = client.DownloadString(stringUrl);
            }

            List<Uri> links = new List<Uri>();
            var NoImageUrl = "../../Images/NoImage.jpg";
            string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
            MatchCollection matchesImgSrc = Regex.Matches(htmlCode, regexImgSrc,
                RegexOptions.IgnoreCase | RegexOptions.Singleline);
            try
            {
                if (matchesImgSrc.Count > 0)
                {
                    foreach (Match m in matchesImgSrc)
                    {
                        string href = m.Groups[1].Value;
                        var newhref = new Uri(href).ToString().ToLower();
                        if ((newhref.Contains("/media/") || newhref.Contains("/assets/img/") ||
                             newhref.Contains("/assets/images/") || newhref.Contains("/assets/") ||
                             newhref.Contains("/images/article/") ||
                             newhref.Contains("/images/") || newhref.Contains("/files/"))
                             && !newhref.Contains("/ads/") && (!newhref.Contains(".png") && (newhref.Contains(".jpg") || newhref.Contains(".jpeg")) && (!newhref.Contains(".gif"))
                             && (!newhref.Contains("height")) && (!newhref.Contains("width"))
                             ))
                        {
                            return newhref;
                        }
                    }
                }
                return null;
            }

            catch (Exception e)
            {
                return null;
            }

        }

        public static string GetFacebookShareLink(int feedpostId)
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            List<FeedPost> list = (from f in connection.GetAll<FeedPost>()
                                   where f.FeedPostId == feedpostId
                                   select f).ToList();

            FeedPost feedpost = new FeedPost();
            if (list.Count > 0) feedpost = list[0];

            var postUrl = ConfigurationManager.AppSettings["ShareLinkUrl"].ToString() + "/Feed/" + feedpost.FeedPostId + "/" + feedpost.Title.Replace("'", "`");
            var fbsharelink = "javascript:popup_share('http://www.facebook.com/sharer.php?u=" + postUrl + "&t=Share',800,320)";
            return fbsharelink.ToString();

        }

        public static string GettwitterShareLink(int feedpostId)
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            List<FeedPost> list = (from f in connection.GetAll<FeedPost>()
                                   where f.FeedPostId == feedpostId
                                   select f).ToList();

            FeedPost feedpost = new FeedPost();
            if (list.Count > 0) feedpost = list[0];

            var postUrl = ConfigurationManager.AppSettings["ShareLinkUrl"].ToString() + "/Feed/" + feedpost.FeedPostId + "/" + feedpost.Title.Replace("'", "`");
            var twittersharelink = "javascript:popup_share('http://twitter.com/home?status=" + postUrl + "',800,320)";
            return twittersharelink.ToString();

        }


        public static string RemoveSpecialCharacters(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if (((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') && c != 46)
                    sb.Append(c);

                if (c == 32 || c == 46)
                    sb.Append('-');

            }
            return sb.ToString();
        }

        public static int GetSourceFeedCount(int sourceId)
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            List<FeedPost> list = (from f in connection.GetAll<FeedPost>()
                                   where f.SourceId == sourceId
                                   select f).ToList();

            return list.Count();
        }

        public static int GeTagFeedsCount(int categoryId)
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            List<FeedPost> list = (from f in connection.GetAll<FeedPost>()
                                   where f.CategoryId == categoryId
                                   select f).ToList();

            return list.Count();

        }

        public static string GetTagbyCategory(int categoryId)
        {
            var connection = new RepositoryBaseMongo("Category");
            List<Category> list = (from f in connection.GetAll<Category>()
                                   where f.CategoryId == categoryId
                                   select f).ToList();
            Category category = new Category();
            if (list.Count > 0) category = list[0];
            return category.Tag;
        }

        public static int GetCommentCount(int feedid)
        {
            var connection = new RepositoryBaseMongo("FeedComment");
            List<FeedComment> list = (from f in connection.GetAll<FeedComment>()
                                      where f.FeedId == feedid
                                      select f).ToList();

            return list.Count();
        }


        public static bool DownloadImageFromUrl(string imageUrl, string saveurl)
        
        {
            try
            {
                WebClient wc = new WebClient();
                wc.DownloadFile(imageUrl, saveurl);
                Thread.Sleep(1000);
                return true;
            }
            catch (Exception x)
            {
                return false;
            }
        }

        public static string GetUserNamebyId(int id)
        {
            var connection = new RepositoryBaseMongo("Users");
            List<Users> list = (from f in connection.GetAll<Users>()
                                 where f.UserId == id
                                 select f).ToList();
            Users sources = new Users();
            if (list.Count > 0) sources = list[0];
            return sources.UserName;
        }

        public static string GetSourceNameById(int id)
        {
            var connection = new RepositoryBaseMongo("Source");
            List<Source> list = (from f in connection.GetAll<Source>()
                                 where f.SourceId == id
                                 select f).ToList();
            Source sources = new Source();
            if (list.Count > 0) sources = list[0];
            return sources.ShortDescription;
        }

        public static string GetImageByAlbumId(int albumId)
        {
            var image = "";
            var connection = new RepositoryBaseMongo("Photos");
            var list = connection.GetAll<Photos>().LastOrDefault(x => x.AlbumId == albumId );
            if (list != null)
            {
                image = list.PhotoUrl;
            }
            return image;
        }
        public static string GetImageByPhotoId(int photoId)
        {
            var image = "";
            var connection = new RepositoryBaseMongo("Photos");
            var list = connection.GetAll<Photos>().FirstOrDefault(x => x.PhotoId == photoId);
            if (list != null)
            {
                image = list.PhotoUrl;
            }
            return image;
        }

        public static string GetFeedLikeCount(int feedpostid)
        {
            var connection = new RepositoryBaseMongo("FeedLikes");
            var count = connection.GetAll<FeedLikes>().Count(x => x.FeedPostId == feedpostid && x.isLiked);
            var countstring = count + " people liked this.";
            return countstring;
        }

        public static string GetLikeOrUnlike(int feedid)
        {
            var connection = new RepositoryBaseMongo("FeedLikes");
            var count = connection.GetAll<FeedLikes>().Count(x => x.FeedPostId == feedid && x.UserId==WebSecurity.CurrentUserId);
            if (count > 0)
            {
                return "Unlike";
            }
            return "Like";
        }

        #region Profile

        public static List<FriendRequest> FriendRequestList(int userId)
        {
            var connection = new RepositoryBaseMongo("FriendRequest");
            var list = connection.GetAll<FriendRequest>().ToList().Where(x => x.ReceiverId == userId && !x.IsRead).ToList();
            return list;
        }

        public static string GetCurrentUserFullName()
        {
            var fullName = "";
            var connection = new RepositoryBaseMongo("Users");
            var data = connection.GetAll<Users>();
            var user = data.FirstOrDefault(u => u.UserId == WebSecurity.CurrentUserId);
            if (user != null)
            {
                fullName = user.FirstName + " " + user.LastName;

            }
            return fullName;
        }
        public static string GetCurrentUserFullName(int userId)
        {
            var fullName = "";
            var connection = new RepositoryBaseMongo("Users");
            var data = connection.GetAll<Users>();
            var user = data.FirstOrDefault(u => u.UserId == userId);
            if (user != null)
            {
                fullName = user.FirstName + " " + user.LastName;

            }
            return fullName;
        }
        public static string GetCurrentUserImage()
        {
            var image = "";
            var connection = new RepositoryBaseMongo("Users");
            var data = connection.GetAll<Users>();
            var user = data.FirstOrDefault(u => u.UserId == WebSecurity.CurrentUserId);
            if (user != null)
            {
                image = user.ImageUrl;

            }
            return image;
        }
        public static string GetCurrentUserImage(int userId)
        {
            var image = "";
            var connection = new RepositoryBaseMongo("Users");
            var data = connection.GetAll<Users>();
            var user = data.FirstOrDefault(u => u.UserId == userId);
            if (user != null)
            {
                image = user.ImageUrl;

            }
            return image;
        }

        public static string GetUserImageByUserName(string username)
        {
            var image = "";
            var connection = new RepositoryBaseMongo("Users");
            var data = connection.GetAll<Users>().Where(u => u.UserName.ToLower() == username.ToLower());

            if (data.Any())
            {
                image = data.FirstOrDefault().ImageUrl;

            }
            return image;
        }

        public static int FindingFriend(int userId)
        {
            var connection = new RepositoryBaseMongo("FriendRequest");
            var list = connection.GetAll<FriendRequest>().ToList().Where(x => x.ReceiverId == userId  && !x.IsRead).ToList();
            return list.Count();

        }

        public static IEnumerable<DataMongo.Entities.Group> GetGroupList()
        {
            var connection = new RepositoryBaseMongo("Group");
            var connectionG = new RepositoryBaseMongo("GroupMember");
            var member = connectionG.GetAll<GroupMember>().Where(x => x.MemberID == WebSecurity.CurrentUserId).Select(x => x.GroupId).ToList();
            var group = connection.GetAll<DataMongo.Entities.Group>().Where(x => member.Contains(x.GroupId)).ToList();
            return group;
        }

        public static string GetGroupNamebyId(int groupId)
        {
            var connection = new RepositoryBaseMongo("Group");
            var group = connection.GetAll<DataMongo.Entities.Group>().Where(x => x.GroupId == groupId);
            if (group.Any())
                return group.FirstOrDefault().GroupName;
            return string.Empty;
        }

        public static List<int> GetFriendList()
        {
            var userId = WebSecurity.CurrentUserId;
            var connection = new RepositoryBaseMongo("FriendList");
            var first = connection.GetAll<FriendList>().Where(x => x.MyId == userId ).Select(x=>x.FriendId);
            var second = connection.GetAll<FriendList>().Where(x => x.FriendId == userId).Select(x => x.MyId);

            return first.Union(second).ToList();
        }


        public static string GetCategoryNameById(int id)
        {
            var connection = new RepositoryBaseMongo("Category");
            List<Category> list = (from f in connection.GetAll<Category>()
                                   where f.CategoryId == id
                                   select f).ToList();
            Category category = new Category();
            if (list.Count > 0) category = list[0];
            return category.ShortDescription;
        }

        public static List<int> GetFriendList(int userId)
        {
            
            var connection = new RepositoryBaseMongo("FriendList");
            var first = connection.GetAll<FriendList>().Where(x => x.MyId == userId).Select(x => x.FriendId);
            var second = connection.GetAll<FriendList>().Where(x => x.FriendId == userId).Select(x => x.MyId);

            return first.Union(second).ToList();
        }
        public static List<string> GetFriendListForImage()
        {
            var userId = WebSecurity.CurrentUserId;
            var connection = new RepositoryBaseMongo("FriendList");
            var first = connection.GetAll<FriendList>().Where(x => x.MyId == userId).Select(x =>
                x.FriendId +"_"+GetCurrentUserImage(x.FriendId)
                );
            var second = connection.GetAll<FriendList>().Where(x => x.FriendId == userId).Select(x =>
                
               
                 x.MyId +"_"+GetCurrentUserImage(x.MyId));

            return first.Union(second).ToList();
        } 
        #endregion
        #region Group
        public static bool IsGroupAdmin(int groupId)
        {
            var connectionG = new RepositoryBaseMongo("GroupMember");
            var member = connectionG.GetAll<GroupMember>().Where(x => x.MemberID == WebSecurity.CurrentUserId && x.GroupId == groupId && x.IsAdmin).ToList();
            if (member.Any())
            {
                return true;
            }
            return false;

        }

        public static int GroupMemberCount(int groupId)
        {
            var connectionG = new RepositoryBaseMongo("GroupMember");
            var member = connectionG.GetAll<GroupMember>().Where(x=>x.GroupId == groupId).ToList();
            return member.Count();
        }
        #endregion

        public static List<ChatUser> GetUserchatFriendList(List<ChatUser> Userlist)
        {
            if (Userlist.Any())
            {
                var currentUserid = WebSecurity.CurrentUserId;
                var connection = new RepositoryBaseMongo("FriendList");
                var first = connection.GetAll<FriendList>().Where(x => x.MyId == currentUserid).Select(x => x.FriendId);
                var second = connection.GetAll<FriendList>().Where(x => x.FriendId == currentUserid).Select(x => x.MyId);
                var idlist = first.Union(second).ToList();
                List<string> usernames = new List<string>();
                foreach (var i in idlist)
                {
                    usernames.Add(UtilityService.GetUserNamebyId(i));
                }
                var returnuserlist = Userlist.Where(x => usernames.Contains(x.Email)).ToList();
                return returnuserlist;
            }

            return Userlist;
        }
    }
}
